package com.vf.admin.platform.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.vf.admin.common.BaseController;
import com.vf.admin.common.Constants;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.platform.entity.Element;
import com.vf.admin.platform.entity.Menu;
import com.vf.admin.platform.entity.RoleMenu;
import com.vf.admin.platform.entity.User;
import com.vf.admin.platform.service.*;
import com.vf.admin.utils.StringEx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.*;

/**
 * 平台用户登录
 */
@Controller
@RequestMapping("/web")
public class LoginController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    RoleService roleService;
    @Autowired
    MenuService menuService;
    @Autowired
    UserService userService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    RoleMenuElementService roleMenuElementService;
    @Resource
    RedisUtil redisUtil;
    @Autowired
    DefaultKaptcha defaultKaptcha;

    /**
     * 登录验证
     * @param
     *         username:登录用户名
     *         password：密码
     *         vercode：验证码
     *         random：随机数
     * @return
     *         resMap
     *            st  状态：1、登录成功 -1、登录失败
     *            mes 提示说明
     */
    @RequestMapping("/login.html")
    public String validation(String username, String password, String vercode, ModelMap map){
        String method = request.getMethod();
        if(method.trim().toLowerCase().equals("get")){
            return "/web/login";
        }
        Map<String, String> resMap = new HashMap<String,String>();
        if(StringUtils.isEmpty(username)){
            return this.error("用户名不能为空","/web/login");
        }
        if(StringUtils.isEmpty(password)){
            return this.error("密码不能为空","/web/login");
        }

        if(StringEx.isNull(vercode)){
            return this.error("验证码不能为空!","/web/login");
        }
        Object oldVercode = redisUtil.get(vercode);
//        System.out.println("登录oldVercode:"+oldVercode);
//        if(oldVercode==null || !oldVercode.equals(vercode)){
//            return this.error("验证码不正确或已失效!","/web/login");
//        }

        //验证码通过，立即删除验证码
        redisUtil.del(vercode);

        Map<String,Object> paraMap = new HashMap<String,Object>();
        paraMap.put("loginname",username);
        List<User> userList =  userService.findList(paraMap,null);
        if(userList==null || userList.size()<=0){
            return this.error("用户名或密码不正确!","/web/login");
        }

        User user = userList.get(0);
        if(!user.getPassword().trim().equals(password.trim())){
            return this.error("用户名或密码不正确!","/web/login");
        }

        //写入登录缓存标识
//        String token = UUID.randomUUID().toString();
//        logger.info("登录成功token："+token);


        Map<String,Object> resultMap = new HashMap<String,Object>();
//        resultMap.put(Constants.access_token,token);

        //查询用户拥有的菜单和标签对应的接口权限
        List<String> menuStrList = new ArrayList<String>();
        Map<String,Object> paramap = new HashMap<String,Object>();
        paramap.put("userid",user.getId());
        List<Menu> list = userRoleService.findMenuListByUserId(paramap);
        if(list!=null && list.size()>0){
             for(Menu menu : list){
                 menuStrList.add(menu.getLinks());
            }
        }
        paramap.clear();

        Map<String,Integer> userCacheMap = new HashMap<String,Integer>();
        paramap.put("userid",user.getId());
        List<RoleMenu> roleMenuList = userRoleService.findRoleMenuListByUserId(paramap);
        if(roleMenuList!=null && roleMenuList.size()>0){

            paramap.clear();
            List<Element> elementList = roleMenuElementService.findElementListByRoleId(roleMenuList);
            if(elementList!=null && elementList.size()>0){
                for(Element element : elementList){
//                    System.out.println(element.getLinks()+"____"+user.getId());
                    userCacheMap.put(element.getLinks(),user.getId());
                }
            }
        }

        user.setUserCacheMap(userCacheMap);
        if(user.getUserCacheMap()!=null){
//            System.out.println("userCacheMap.size():"+user.getUserCacheMap().size());
        }
        request.getSession().setAttribute(Constants.access_token, user);
        return "redirect:/web/main.html";
    }

    /**
     * 生成验证码
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @RequestMapping("/kaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
//        String ip = request.getRemoteAddr();
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生产验证码字符串并保存到session中
//            String createText = defaultKaptcha.createText();
//            createText = createText;
            String createText = verifyCode();
            String random = UUID.randomUUID().toString();
            response.setHeader("Access-Control-Expose-Headers", "random");//设置允许浏览器跨域访问的时候，可以获取自定义的header中的random属性
            response.setHeader("random", random);//添加一个自定的header属性

            logger.info("请求验证时的随机验证码:"+createText);
            logger.info("请求验证时的随机字符random:"+random);
            //写入登录缓存标识
            redisUtil.set(createText.toLowerCase(),createText.toLowerCase(),Constants.Kaptcha_effective_time);//有效期
            logger.info("图形验证码已经写入redis:"+createText,createText);

            // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
        }

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();

        //返回base64字符串
//        String imgsrc = "data:image/jpg;base64,"+Base64.byteArrayToBase64(captchaChallengeAsJpeg);
//        return imgsrc;
//        System.out.println("imgsrc:"+imgsrc);

        //返回jpg图片
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    public String verifyCode(){
        String str = "";
//        char[] ch = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
//                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
//                'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
        char[] ch = {'2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K',
                'L', 'M', 'N','P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n',
                'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
        Random random = new Random();
        for (int i = 0; i <4; i++){
            char num = ch[random.nextInt(ch.length)];
            str += num;
        }
        return str;
    }

    /**
     * 退出登录loginout
     */
    @RequestMapping("/loginout")
    public String loginOut(){
        String token = request.getHeader(Constants.access_token);
        Map<String, String> resMap = new HashMap<String,String>();
        Object userObj = redisUtil.get(token);
        if(userObj!=null){
            redisUtil.del(token);
        }
        return this.sucess("redirect:/web/platform/jinbilist.html ");
    }

    /**
     * 获取当前登录用户信息
     */
//    @RequestMapping("/user")
//    @ResponseBody
//    public Result user(HttpServletRequest request){
//        try{
//            String token = request.getHeader(Constants.access_token);
//            Map<String, Object> resMap = new HashMap<String,Object>();
//            User user = (User)redisUtil.get(token);
//            UserDto userDto = new UserDto();
//            userDto.setLoginname(user.getLoginname());
//            userDto.setName(user.getName());
//            userDto.setRolename(user.getRolename());
//            Map<String,Object> resultMap = new HashMap<String,Object>();
//
//            resultMap.put("user",userDto);
//            return this.sucess(resultMap);
//        }catch(Exception e){
//            return this.error("获取信息失败，请联系管理员！");
//        }
//    }

}
